<?php

namespace apiend\modules\statistic\models;

use Yii;

/**
 * 店铺排行榜
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class RankStoreSearch extends \common\models\shop\ShopOrder {

    use \common\logics\stats\TimefilterTrait;

    /**
     * @var bool 不使用分页
     */
    public $pagesize = false;

    /**
     * @var integer 限制读取条数
     */
    public $limitSize = 30;

    /**
     * @var bool 不使用分页
     */
    public $counts;

    /**
     * {@inheritdoc}
     */
    public function buildQuery() {
        $query = static::find()->alias('t')->active();
        $query->andFilterDuration('t.pay_time', $this->beginTime, $this->endTime);
        $query->select([
            '*',
            'amount' => 'sum(t.pay)',
            'counts' => 'count(*)',
        ]);
        $query->groupBy([
            'store_id'
        ]);
        $query->orderBy([
            'amount' => SORT_DESC
        ]);
        $query->debug();
        return $query;
    }

    /**
     * {@inheritdoc}
     */
    public function search($params = []) {
        if (!$this->validate()) {
            return [];
        }
        return parent::search($params);
    }

    /**
     * {@inheritdoc}
     */
    public function fields() {
        return [
            'id',
            'store',
            'amount' => function() {
                return round($this->amount, 2);
            },
            'counts' => function() {
                return intval($this->counts);
            },
        ];
    }

}
